﻿package net.wangit.adm.role;

import java.util.Iterator;
import java.util.Map;

import net.wangit.context.LocalContext;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.TreeFactory;
import net.wangit.view.tree.Tree;


public abstract class PrivilegeTreeFactory extends TreeFactory {

	private static final String PRIVILEGE_ICON = "/domain/adm/u/privileges.png";
	private static final String UNIT_PRIVILEGE_ICON = "/domain/adm/u/unit_privileges.png";
	private static final String ENUMERATION_PRIVILEGE_ICON = "/domain/adm/u/enum_privileges.png";
	public static final String CATALOG_CSS = "catalog";
	private String domain;
	private Map privileges;
	private boolean disabled;
	private PrivilegeTreeUtil util;

	public PrivilegeTreeFactory() {
	}

	public Tree createTree(String treeDomain) throws Exception {
		net.wangit.context.ActionContext ac = LocalContext.getLocalContext()
				.getActionContext();
		domain = getDomain();
		privileges = getPrivileges();
		disabled = isDisabled();
		util = new PrivilegeTreeUtil(domain, privileges, disabled);
		net.wangit.jdbc.DB db = DBHelper.getDomainDB(domain);
		Tree root = getTree("_privileges_");
		root.setIcon("/domain/adm/u/privileges.png");
		Tree ups = getTree("_ups_");
		root.add(ups);
		PrivilegeUnitTree unitTree = new PrivilegeUnitTree(domain, privileges,
				disabled, util);
		ups.setIcon("/domain/adm/u/unit_privileges.png");
		unitTree.addTree(ac, db, ups);
		int upCount = ups.countLeaf();
		ups.setName((new StringBuilder("单元 ")).append(upCount).toString());
		Tree eps = getTree("_eps_");
		root.add(eps);
		eps.setIcon("/domain/adm/u/enum_privileges.png");
		PrivilegeEnumerationTree enumerationTree = new PrivilegeEnumerationTree(
				disabled, util);
		enumerationTree.addTree(ac, db, eps);
		int epCount = eps.countLeaf();
		eps.setName((new StringBuilder("枚举 ")).append(epCount).toString());
		root.setName((new StringBuilder("权限点(")).append(
				getDomainPrivilegeCount()).append("/")
				.append(upCount + epCount).append(")").toString());
		return root;
	}

	private int getDomainPrivilegeCount() {
		int count = 0;
		String prefix = (new StringBuilder(String.valueOf(domain))).append(",")
				.toString();
		for (Iterator keys = privileges.keySet().iterator(); keys.hasNext();) {
			String key = (String) keys.next();
			if (key.startsWith(prefix))
				count++;
		}

		return count;
	}

	private Tree getTree(String id) {
		Tree tree = new Tree();
		tree.setId(id);
		tree.setCheckValue("-");
		tree.setCss("catalog");
		if (disabled)
			tree.setCheckAttribute("style='display:none'");
		return tree;
	}

	protected abstract String getDomain();

	protected abstract Map getPrivileges() throws Exception;

	protected abstract boolean isDisabled();
}
